package models

import (
	"strconv"
	"strings"
)

type UserLibrary struct {
	Id           int `json:"id" xorm:"not null pk autoincr comment('主键') INT(11)"`
	UserId int `json:"user_id" xorm:"not null comment('用户id')  INT(11)"`
	QuestionId int `json:"question_id" xorm:"not null comment('题目主键') INT(11)"`
	Inlibrary int `json:"inlibrary" xorm:"not null comment('题目主键') INT(11)"`


}
var userlibrary ="user_library"

func(uq *UserLibrary) GetRow() bool {
	has, err := mEngine.Get(uq)
	if err==nil &&  has  {
		return true
	}
	return false
}
func(uq *UserLibrary) UpdateInLibrary(ids string,inlibrary int) error {
	questionIds:=strings.Split(ids,",")
	questionIdsArr := make([]int, len(questionIds))
	var err error
	for i, v := range questionIds {
		questionIdsArr[i], err = strconv.Atoi(v)
		if err != nil {
			continue //如果传入非数组，那么忽略
		}
	}
	session := mEngine.NewSession()
	defer session.Close()
	// add Begin() before any action
	if err := session.Begin(); err != nil {
		// if returned then will rodefer session.Close()llback automatically
		return err
	}
	for _, questionId := range questionIdsArr {
		if inlibrary == 0 {
			//出库
			if _, err := mEngine.Exec("delete from "+userlibrary+" where user_id=? and question_id =? ", uq.UserId, questionId); err != nil {
				return err
			}

		}else{
			uq.QuestionId=questionId
			if uq.GetRow() {
				if _, err := mEngine.Exec("update "+userlibrary+" set inlibrary=1 where user_id=? and question_id =? ",
					uq.UserId,uq.QuestionId); err != nil {
					return err
				}
			}else{
				uq.Inlibrary=inlibrary
				if _,err :=mEngine.Exec("insert into "+userlibrary+"  (id,user_id,question_id,inlibrary) values (0,?,?,?)",
					uq.UserId,uq.QuestionId,uq.Inlibrary); err != nil {
					return err
				}


			}
		}
	}
	return session.Commit()
}